package com.FTP;

import java.util.ArrayList;
import java.util.List;

import org.apache.ftpserver.FtpServer;
import org.apache.ftpserver.FtpServerFactory;
import org.apache.ftpserver.ftplet.Authority;
import org.apache.ftpserver.ftplet.FtpException;
import org.apache.ftpserver.ftplet.UserManager;
import org.apache.ftpserver.listener.ListenerFactory;
import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
import org.apache.ftpserver.usermanager.SaltedPasswordEncryptor;
import org.apache.ftpserver.usermanager.impl.BaseUser;
import org.apache.ftpserver.usermanager.impl.WritePermission;

public class ftpServer {
	
	private FtpServer server=null;
	private List<Authority> auths = new ArrayList<Authority>();
	private PropertiesUserManagerFactory userManagerFactory = null;
	private UserManager userManager =null;
	private String path;

	public ftpServer(int port, String path) {
        FtpServerFactory serverFactory = new FtpServerFactory();
        userManagerFactory = new PropertiesUserManagerFactory();
        userManagerFactory.setPasswordEncryptor(new SaltedPasswordEncryptor());
        userManager = userManagerFactory.createUserManager();
       
        ListenerFactory listenerFactory = new ListenerFactory();
        listenerFactory.setPort(port);
        serverFactory.addListener("default",listenerFactory.createListener());
        serverFactory.setUserManager(userManager);

        server = serverFactory.createServer();
        this.path = path;

    }
	/**
	 * add an account to this server
	 * @param account
	 */
	public void addAccount(Account account)
	{
        BaseUser user = new BaseUser();
        user.setName(account.username);
        user.setPassword(account.password);
        user.setHomeDirectory(path);  
        Authority auth = new WritePermission();
        auths.add(auth);
        user.setAuthorities(auths);
        try {
            userManager.save(user);
        } catch (FtpException e1) {
            e1.printStackTrace();
        }
	}
	/**
	 * start the server
	 */
	public void startServer()
	{
        try {
            server.start();
        } catch (FtpException e) {
            e.printStackTrace();
        }	
	}
	/**
	 * stop the server
	 */
	public void endServer()
	{
		server.stop();
	}
}
